var spider = {
	tasks : []
};
(function(s){
	var page, config, fs, system;

	var UA = {
		mac_chrome : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.16 (KHTML, like Gecko) Chrome/24.0.1305.3 Safari/537.16",
		iphone : 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3'
	};
	config = {
		userAgent : UA.mac_chrome,
		jqueryPath : 'jquery-1.7.1.js',
		browserJsPath: 'spider_browser.js'
	};
	page = createPage();

	function createPage(){
		var p = require('webpage').create();
		p.settings.userAgent = config.userAgent
		p.settings.XSSAuditingEnabled = false;
		//IMPORTANT!! Allow XHR crossDomain!
		p.settings.webSecurityEnabled = false;
		p.onConsoleMessage = function(msg) {
			if(msg == 'CMD:exit'){
				phantom.exit();
				return;
			}
			if(msg == 'CMD:done'){
				s.done();
				s.nextTask();
			}
			console.log(msg);
		};
		return p;
	}

	s.done = function(){
		s.crawling =false;
	};

	s.nextTask = function(){
		if (s.crawling) {return};
		console.log('s.tasks.length: ' + s.tasks.length);
		if(s.tasks.length){
			execute(s.tasks.shift());
		} else {
			phantom.exit();
		}
	};

	function execute(rule){
		console.log('s.crawling:' + s.crawling);
		if (s.crawling) {return};
		s.crawling = true;
		setTimeout(function(){
			crawl(rule.url, rule.handler);
		}, parseInt(rule.delay) || 0);
	}

	function crawl(url, handler){
		console.log('Current: ' + url);
		page.open(url, function(){
			var jqueryReady = page.injectJs(config.jqueryPath);
			var browserJsReady = page.injectJs(config.browserJsPath);
			console.log('jqueryReady: ', jqueryReady);
			// console.log(page.evaluate(function(){ return window.location.href;}) +'\n');
				//避免url跳转执行原url相关代码
			//if(url == page.evaluate(function(){ return window.location.href})){
				page.evaluate(handler);
			//}
			/*
			page.evaluate(function(){
				if(window.location.href == url){
					handler();	
				}
			});
			*/
		});
	}


	s.addTask = function (rule){
		if(!rule.url || !rule.handler){
			return false;
		}
		s.tasks.push(rule);
		s.nextTask();

		// setTimeout(function(){
		// 	crawl(rule.url, rule.handler);
		// }, parseInt(rule.delay) || 0);
	}

})(spider);

/*
spider.addRule({
	//url:'http://www.diandian.com/tag/美女',
	delay: 0,
	url:'http://www.diandian.com/tag/%E7%BE%8E%E5%A5%B3',
	handler: function(){
		var toPost = [];
		$('img.feed-img').each(function(){
			var oriInfo = $(this).attr('data-origin-info');
			if(oriInfo && oriInfo.split(":").length >= 5 ){
				var infos = oriInfo.split(":"),
					pic_url = infos[0] + ":" + infos[1],
					width = parseFloat(infos[2]),
					height = parseFloat(infos[3]),
					key = infos[4];
				console.log(pic_url+"   " + width + "   " + height + "   " + key);
				toPost.push({
					'pic_url' : pic_url,
					'pic_key' : 'diandian_' + key,
					'source' : 'diandian'
				});
			}
			//console.log($(this).attr('data-origin-info') );
		});
		
		$.post('http://admin.shenmu.com/remote/new',{pics: JSON.stringify(toPost)}, function(text){
			console.log(text);
			//console.log("CMD:exit");
			//phantom.exit();
		});
	}
});
*/
/*
spider.addRule({
	delay: 0,
	url: 'http://image.baidu.com/i?tn=list&word=liulan#%E7%BE%8E%E5%A5%B3|%E5%85%A8%E9%83%A8',
	handler: function(){
		var toPost = [];
		$('img[obj_url]').each(function(){
			var pic_url = $(this).attr('obj_url'),
				pic_key = 'baidu_' + $(this).attr('src');
			toPost.push({
				'pic_url' : pic_url,
				'pic_key' : pic_key,
				'source'  : 'baidu'
			});
		});

		$.post('http://admin.shenmu.com/remote/new',{pics: JSON.stringify(toPost)}, function(text){
			console.log(text);
			//console.log("CMD:exit");
			//phantom.exit();
		});
	}
});
*/


/*
var page = require('webpage').create(),
    system = require('system');
var jqueryPath = 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
//var jqueryPath = 'jquery-1.7.1.js';


//var url = "http://www.diandian.com/tag/";
var url = "http://www.diandian.com/tag/%E7%BE%8E%E5%A5%B3";

page.onAlert = function(msg) {
    console.log(msg);
};


function handleDom(status){
	if (status !== 'success') {
        console.log('Unable to load the address!');
        return;
    }
    console.log("loaded.")

	page.includeJs(jqueryPath, function(){
		page.evaluate(function(){
			console.log("includeJs success.");
			var toPost = [];
			$('img.feed-img').each(function(){
				var oriInfo = $(this).attr('data-origin-info');
				if(oriInfo && oriInfo.split(":").length >= 5 ){
					var infos = oriInfo.split(":"),
						pic_url = infos[0] + ":" + infos[1],
						width = parseFloat(infos[2]),
						height = parseFloat(infos[3]),
						key = infos[4];
					console.log(pic_url+"   " + width + "   " + height + "   " + key);
					toPost.push({
						'pic_url' : pic_url,
						'pic_key' : 'diandian_' + key,
						'source' : 'diandian'
					});
				}
				//console.log($(this).attr('data-origin-info') );
			});
			
			// $('<iframe name="_hide_frame" id="_hide_frame" src="http://admin.shenmu.com/remote/new"></iframe>').appendTo(document.body);
			// var tpl = '<form method="post" action="%url%" target="_hide_frame"><input name="pics" value="%pics%"></form>',
			// 	htmlStr = tpl.replace("%pics%", JSON.stringify(toPost)).replace("%url%","http://admin.shenmu.com/remote/new");

			// var form = $(htmlStr);
			//form.appendTo(document.body);
			//form.submit();
			
			$.post('http://admin.shenmu.com/remote/new',{pics: JSON.stringify(toPost)}, function(text){
				console.log(text);
				console.log("CMD:exit");
				//phantom.exit();
			});
			 
			//in page
			console.log("IMG count: " + $('img').length + " .");
		});
		
		//phantom.exit();
	});

}


// page.onInitialized = function() {
//     page.evaluate(function() {
//         document.addEventListener("DOMContentLoaded", function() {
            
//         }, false);
//     });
// };


//main part
page.open(url, handleDom);
*/